/**
 * rust中常见用的三方库
 * 1.Serde序列化和反序列化
 * 2.rand随机数生成
 * 3.async-std异步编程
 * 4.log日志
 * 5.strum字符串处理
 * 6.test测试框架
 * 7.csv处理csv文件
 * 8.chrono日期和时间处理
 */
use serde_derive::{Deserialize, Serialize};
use rand::{thread_rng, Rng};
use serde_json;
use async_std::task;
use async_std::prelude::*;
use async_std::fs::File;
use log::{error, info, warn, trace, debug};
use log4rs;
use std::{error::Error, io, process};
use chrono::prelude::*;

#[derive(Debug)]
#[derive(Serialize, Deserialize)] // 属性让Serde自动为该结构体实现序列化和反序列化方法
struct Person {
    name: String,
    age: i32,
}
fn handle_serde() {
    // 创建一个Person对象
    let person = Person {
        name: "Alice".to_string(),
        age: 30,
    };
    // 将Person对象序列化为JSON字符串
    let serialized = serde_json::to_string(&person).unwrap();
    println!("Serialized: {}", serialized);
    // 将JSON字符串反序列化为Person对象
    let deserialized: Person = serde_json::from_str(&serialized).unwrap();
    println!("Deserialized: {:?}", deserialized);
}

fn handle_rand() {
    // 随机数
    let mut rng = thread_rng();
    let n: u32 = rng.gen_range(0..10);
    let m: f64 = rng.gen_range(-40.0..1.3e5);
    println!("随机数{},{}", n, m);
}

fn handle_log() {
    // 方式一
    // let sys_file = log4rs::append::file::FileAppender::builder()
    // .encoder(Box::new(log4rs::encode::pattern::PatternEncoder::new("{d} - {m}{n}")))
    // .build("logs/sys.log")
    // .unwrap();
    // let config = log4rs::Config::builder()
    // .appender(log4rs::config::Appender::builder()
    // .build("sys", Box::new(sys_file)))
    // .logger(log4rs::config::Logger::builder()
    //         .appender("sys")
    //         .build("syslog", log::LevelFilter::Info),
    // ).build(
    //     log4rs::config::Root::builder()
    //         .build(log::LevelFilter::Info),
    // ).unwrap();
    // log4rs::init_config(config).unwrap();
    // log::info!(target:"syslog","Input sys log");
    // 方式二
    log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
    log::info!(target:"app","Input sys log");
    log::info!(target:"app1","Input sys log");
    log::info!(target:"app11","Input sys log"); // yaml没配置所以不会写入到.log文件
}

 async fn handle_async(data: &str) -> std::io::Result<()> {
    let mut file = File::create("file.txt").await?;
    file.write_all(data.as_bytes()).await?;
    error!("error message");
    Ok(())
}

fn handle_strum() {
    
}

#[derive(Debug, serde::Deserialize)]
struct Record {
    city: String,
    region: String,
    country: String,
}
fn handle_csv_width_serde() -> Result<(), Box<dyn Error>> {
    let data = "\
city,region,country
Boston,United States,4628910
Concord,United States,42695
";
    let mut rdr = csv::Reader::from_reader(data.as_bytes());
    for result in rdr.deserialize() {
        // Notice that we need to provide a type hint for automatic
        // deserialization.
        let record: Record = result?;
        println!("{:?}", record);
    }
    Ok(())
}
fn handle_csv() -> Result<(), Box<dyn Error>> {
    let data = "\
city,country,pop
Boston,United States,4628910
Concord,United States,42695
";
    let mut rdr = csv::Reader::from_reader(data.as_bytes());
    for result in rdr.records() {
        let record = result?;
        println!("{:?}", record);
    }
    Ok(())
}

fn handle_chrono() {
    let utc: DateTime<Utc> = Utc::now();       
    let local: DateTime<Local> = Local::now(); 
    let timestamp = DateTime::timestamp(&utc); // 时间戳
    let format = utc.format("%Y-%m-%d %H:%M:%S").to_string(); // 秒
    let timestamp_millis = utc.timestamp_millis(); // 毫秒
    println!("{},{},{},{},{}", utc, local, timestamp, format, timestamp_millis);
}

fn main() {
    handle_serde();
    handle_rand();
    handle_log();
    let _ = task::block_on(handle_async("hello world"));
    handle_strum();
    if let Err(err) = handle_csv() {
        println!("error running example: {}", err);
        process::exit(1);
    };
    if let Err(err) = handle_csv_width_serde() {
        println!("error running example: {}", err);
        process::exit(1);
    }
    handle_chrono();
    println!("Hello, world!");
}
